package com.bo.redis.limit;

/**
 * 漏桶限流算法
 *
 * @Author: gpb
 * @Date: 2025/2/3 21:17
 * @Description:
 */
public class LeakyBucketLimiter implements TrafficLimiter {
    // 容量
    private int capacity = 100;
    // 速率
    private int rate = 10;
    // 当前容量
    private int current = 20;
    // 上次时间
    private long lastTime = System.currentTimeMillis();

    @Override
    public boolean limit() {
        long now = System.currentTimeMillis();
        current = Math.max(0, current - (int) ((now - lastTime) * rate / 1000));
        lastTime = now;
        // 超过容量，返回true
        if (current + 1 >= capacity) {
            return true;
        }
        current++;
        return false;
    }
}
